package com.gjb6.customer.account.Login;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import com.gjb6.customer.R;
import com.gjb6.customer.account.AccountManager;
import com.gjb6.customer.account.ParamKey;
import com.gjb6.customer.account.UrlCenter;
import com.gjb6.customer.app.MyApplication;
import com.gjb6.customer.common.http.MyHttpRequest;
import com.gjb6.customer.utils.FragmentUtils;
import com.pachong.android.baseuicomponent.activity.BaseActivity;
import com.pachong.android.framework.httprequest.IHttpRequest;
import com.pachong.android.framework.httprequest.responsecallbacks.DataRequestListener;
import com.pachong.android.frameworkbase.dialog.ProgressFragment;
import com.pachong.android.frameworkbase.utils.EasyToast;
import com.pachong.android.frameworkbase.utils.MD5Util;
import com.pachong.android.frameworkbase.utils.RegularUtils;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.Bind;
import butterknife.OnClick;

import static android.R.attr.type;
import static com.gjb6.customer.common.web.MobileFunImpl.getMessageDao;


public class ForgetActivity extends BaseActivity {

    @Bind(R.id.itetForgetPhone)
    EditText mItetForgetPhone;
    @Bind(R.id.itetForgetCode)
    EditText mItetForgetCode;
    @Bind(R.id.itetForgetPassWord)
    EditText mItetForgetPassWord;
    @Bind(R.id.tv_forget_code)
    TextView mTvForgetCode;
    private static final int CATPCHA_TYPE_REGISTER = 2;
    @Bind(R.id.getForgetCode)
    TextView mGetForgetCode;
    private MyCountDownTimer mc;
    private int type;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        type = getIntent().getIntExtra("type", -1);
        Log.e("接收到的type",type+"");
        initToolsBar();
    }

    private void initToolsBar() {
        setTitle("忘记密码");
        getCustomToolbar().addLeftImageButton(R.mipmap.icon_back1, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mc!=null){
                    mc.cancel();
                }
                finish();
            }
        });

    }

    public static void start(Activity activity) {
        Intent intent = new Intent(activity, ForgetActivity.class);
        activity.startActivity(intent);
    }

    public static void start(Activity activity,int type) {
        Intent intent = new Intent(activity, ForgetActivity.class);
        intent.putExtra("type",type);
        activity.startActivity(intent);
    }

    public static void start(Context context) {
        Intent intent = new Intent(context, ForgetActivity.class);
        context.startActivity(intent);
    }
    public static void start(Context context,int type) {
        Intent intent = new Intent(context, ForgetActivity.class);
        intent.putExtra("type",type);
        context.startActivity(intent);
    }

    @Override
    public View createDataView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.activity_forget, null);
    }

    @OnClick({R.id.getForgetCode, R.id.btn_forget})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.getForgetCode:
                sendCheckCode();
                break;
            case R.id.btn_forget:
                putForgetMessage();
                break;
        }
    }

    private void putForgetMessage() {
        if (TextUtils.isEmpty(getPhone())) {
            FragmentUtils.showWarnDialog("手机号不能为空", getSupportFragmentManager());
            return;
        } else if (TextUtils.isEmpty(getPassWord())) {
            FragmentUtils.showWarnDialog("密码不能为空", getSupportFragmentManager());
            return;
        } else if (TextUtils.isEmpty(getYzm())) {
            FragmentUtils.showWarnDialog("请输入验证码", getSupportFragmentManager());
            return;
        } else if (!RegularUtils.isMobileSimple(getPhone())) {
            FragmentUtils.showWarnDialog("输入的手机号有误", getSupportFragmentManager());
            return;
        } else if (!RegularUtils.isPassword(getPassWord())) {
            FragmentUtils.showWarnDialog("密码最多为6-25个字符", getSupportFragmentManager());
            return;
        }
        putMessage();
    }

    private void isRegist() {
        MyHttpRequest request = new MyHttpRequest(this);
        String UrlIsExist = String.format(UrlCenter.ISEXIST, getPhone());
        request.get(UrlIsExist, null, new DataRequestListener<String>(String.class) {
            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }
            @Override
            public void onSuccess(String o) {
                super.onSuccess(o);
                try {
                    JSONObject jsonObject = new JSONObject(o);
                    boolean isExist = jsonObject.optBoolean("value");
                    if(isExist){
                        sendMessage();
                    }else {
                        EasyToast.showToast(ForgetActivity.this,"该账号尚未注册");

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                EasyToast.showToast(ForgetActivity.this,strMsg);
            }
        });
    }

    private String forgetPassWord(){
        if(type==3){
            return  UrlCenter.FORGETPASSWORD;
        }else {
            return  UrlCenter.FORGET_PASSWORD;
        }
    }

    private void putMessage() {

        MyHttpRequest request = new MyHttpRequest(this);
        JSONObject jobj = new JSONObject();
        String enCodePwd = MD5Util.getMd5(getPassWord());//Md5加密
        try {
            jobj.put(ParamKey.LOGIN_NAME, getPhone());
            jobj.put(ParamKey.NEW_PASSWORD, enCodePwd);
            jobj.put(ParamKey.CODE, getYzm());
            request.put(forgetPassWord(), jobj, new DataRequestListener<Object>(Object.class) {
                @Override
                public void onStart(Context context, String url) {
                    super.onStart(context, url);
                }

                @Override
                public void onSuccess(Object o) {
                    super.onSuccess(o);
                    if(mc!=null){
                        mc.cancel();
                    }
                    AccountManager.getTokenInfo().clear();
                    getMessageDao().deleteAll();
                    EasyToast.showToast(ForgetActivity.this, "密码修改成功");
                    LoginActivity.start(ForgetActivity.this);
//                    finish();

                }

                @Override
                public void onFailure(Throwable t, int errorNo, String strMsg) {
                    super.onFailure(t, errorNo, strMsg);
                    EasyToast.showToast(ForgetActivity.this, strMsg);
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private String getPhone() {
        return mItetForgetPhone.getText().toString().trim();
    }

    private String getPassWord() {
        return mItetForgetPassWord.getText().toString().trim();
    }

    private String getYzm() {
        return mItetForgetCode.getText().toString().trim();
    }

    private void sendCheckCode() {
        if (TextUtils.isEmpty(getPhone())) {
            FragmentUtils.showWarnDialog("手机号不能为空", getSupportFragmentManager());
            return;
        } else if (!RegularUtils.isMobileSimple(getPhone())) {
            FragmentUtils.showWarnDialog("输入的手机号有误", getSupportFragmentManager());
            return;
        }
        //先判断是否注册过
        isRegist();
//        sendMessage();
    }

    private void sendMessage() {
        MyHttpRequest request = new MyHttpRequest(this);
        JSONObject jobj = new JSONObject();
        String UrlCaptcha = String.format(UrlCenter.CAPTCHA, getPhone(), type);
        try {
            jobj.put(ParamKey.PHONE, getPhone());
            jobj.put(ParamKey.TYPE, type);
            request.post(UrlCaptcha, jobj, new DataRequestListener<Object>(Object.class) {
                @Override
                public void onStart(Context context, String url) {
                    super.onStart(context, url);
                }

                @Override
                public void onFailure(Throwable t, int errorNo, String strMsg) {
                    super.onFailure(t, errorNo, strMsg);
                    EasyToast.showToast(ForgetActivity.this, strMsg);
                }
                @Override
                public void onSuccess(Object o) {
                    super.onSuccess(o);
                    EasyToast.showToast(ForgetActivity.this, "发送验证码成功!");
                    mGetForgetCode.setClickable(false);
                    mc = new MyCountDownTimer(60000, 1000);
                    mc.start();
                    dismissProgress();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 继承 CountDownTimer 防范
     * <p>
     * 重写 父类的方法 onTick() 、 onFinish()
     */
    class MyCountDownTimer extends CountDownTimer {
        /**
         * @param millisInFuture    表示以毫秒为单位 倒计时的总数
         *                          <p>
         *                          例如 millisInFuture=1000 表示1秒
         * @param countDownInterval 表示 间隔 多少微秒 调用一次 onTick 方法
         *                          <p>
         *                          例如: countDownInterval =1000 ; 表示每1000毫秒调用一次onTick()
         */
        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            mGetForgetCode.setText("重新获取");
            if (!TextUtils.isEmpty(mTvForgetCode.getText())) {
                mGetForgetCode.setClickable(true);
            }
        }

        @Override
        public void onTick(long millisUntilFinished) {
            if (mGetForgetCode != null) {
                mGetForgetCode.setText(millisUntilFinished / 1000 + "s");
            }
        }
    }

    //返回键设置
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK ) {
            if(mc!=null){
                mc.cancel();
            }
            finish();
        }
        return true;
    }


    //显示加载图标
    private ProgressFragment progressFragment = new ProgressFragment();

    private void showProgress() {
        if (!progressFragment.isVisible()) {
            progressFragment.show(getSupportFragmentManager());
        }
    }

    // 隐藏加载图标
    private void dismissProgress() {
        if (progressFragment.isVisible()) {
            progressFragment.dismiss();
        }
    }

}
